package cn.mengfly.testnrz.netty;

import cn.mengfly.testnrz.nio.NioDemoConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Scanner;

public class NettyEchoClient {
    private final int serverPort;
    private final String serverIp;

    Bootstrap b = new Bootstrap();

    public NettyEchoClient(String ip, int port) {
        this.serverIp = ip;
        this.serverPort = port;
    }

    public void runClient() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.remoteAddress(serverIp, serverPort);
            b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(NettyEchoClientHandler.INSTANCE);
                }
            });
            ChannelFuture f = b.connect();
            f.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if (channelFuture.isSuccess()) {
                        System.out.println("EchoClient 客户端连接成功");
                    } else {
                        System.out.println("EchoClient 客户端连接失败");
                    }
                }
            });
            f.sync();
            Channel channel = f.channel();
            Scanner scanner = new Scanner(System.in);
            System.out.println("输入要发送的内容：");
            while (scanner.hasNextLine()) {
                String nextLine = scanner.nextLine();
                byte[] bytes = (new Date() + ">>" + nextLine).getBytes(StandardCharsets.UTF_8);
                ByteBuf buf = channel.alloc().buffer();
                buf.writeBytes(bytes);
                channel.writeAndFlush(buf);
                System.out.println("输入要发送的内容：");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    @ChannelHandler.Sharable
    public static class NettyEchoClientHandler extends ChannelInboundHandlerAdapter {
        public static final NettyEchoClientHandler INSTANCE = new NettyEchoClientHandler();

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            final ByteBuf buf = (ByteBuf) msg;
            final int len = buf.readableBytes();
            byte[] arr = new byte[len];
            buf.getBytes(0, arr);
            System.out.println("client received:" + new String(arr, StandardCharsets.UTF_8));
            buf.release();
//            super.channelRead(ctx, msg);
        }
    }

    public static void main(String[] args) {
        new NettyEchoClient(NioDemoConfig.SOCKET_IP, NioDemoConfig.SOCKET_PORT).runClient();
    }
}
